<script setup>
import { ref, reactive, computed, nextTick, onMounted } from "vue";
import { Toast } from "vant";
import { useUserStore } from "@/stores/user.store.js";
import { useRouter } from "vue-router";
import api from "@/api/api";

//导入图片
import anxinxiu from '@/assets/home/anxinxiu.png'
import avatarIcon from '@/assets/common/avatar.png'
// 使用Vue 3 Composition API
const router = useRouter();
const store = useUserStore();

// refs
const scrollContainer = ref(null);

// 响应式数据
const historyList = ref([]);
const list = ref([]);
const loading = ref(false);
const finished = ref(true);
const refreshing = ref(false);
const isExit = ref(false);
const refirshFinish = ref(false);
const showQuestion = ref(false);
const keyword = ref("");
const questionList = ref(["保养手册", "雨刮有异响怎么办", "什么品牌的轮胎品质好"]);
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 20,
});
const searchLoding = ref(false);

// 从Vuex获取状态
const userData = computed(() => store.userData);

// 方法
const onClickLeft = () => {
  router.back();
};

const onLoad = () => {
  if (refreshing.value) {
    list.value = [];
    refreshing.value = false;
  }
  getMessageList();
};

const onRefresh = () => { };

const clickQuestions = (v) => {
  keyword.value = v;
  onSearch();
};

const getMessageList = async () => {
  let parmas = {
    ...pageInfo,
    storeId: 0,
  };
  let res = await api.message.getMessageList(parmas);
  list.value = [...list.value, ...res.data].filter(
    (item) => item.type == 0 && !item.loading
  );
  const uniqueMap = new Map(list.value.map((item) => [item.autoId, item]));
  list.value = Array.from(uniqueMap.values());

  scrollToBottom(); // 替换原有的$nextTick逻辑
  if (res.data.length < pageInfo.pageSize) {
    finished.value = true;
  } else {
    pageInfo.pageNum++;
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    const container = scrollContainer.value;
    if (container.scrollHeight <= container.clientHeight) {
      return; // 内容不足一屏时不滚动
    }
    if (container) {
      // 获取容器实际样式（包含padding）
      const style = window.getComputedStyle(container);
      const paddingBottom = parseFloat(style.paddingBottom) || 0;

      // 计算正确的滚动位置（包含padding补偿）
      const scrollPosition =
        container.scrollHeight - container.clientHeight + paddingBottom;
      // 计算正确的滚动位置：滚动高度 - 容器可视高度 + 底部padding
      container.scrollTo({
        top: scrollPosition,
        behavior: "smooth",
      });
    }
  });
};

const refreshQuestion = () => {
  isExit.value = !isExit.value;
  // 自动重置动画
  if (isExit.value) setTimeout(() => (isExit.value = false), 500);
};

const onSearch = async () => {
  if (searchLoding.value) return;
  if (keyword.value.trim().length == 0) {
    Toast("咨询的问题不能为空");
  } else {
    searchLoding.value = true;
    let params = {
      accountType: 0,
      storeId: 0,
      text: keyword.value,
      type: 0,
      fileUrl: "",
    };
    list.value.push({
      userId: userData.value.id,
      storeId: params.storeId,
      sendType: 1,
      type: params.type,
      text: keyword.value,
      flleUrl: params.fileUrl,
      sendUserName: userData.value.userName,
      sendUserAvatar: userData.value.avatar,
      createTime: Date.now(),
      loading: true,
    });
    scrollToBottom();
    setTimeout(() => {
      keyword.value = "";
    }, 200);
    await api.message.sendMessage(params)
      .catch(() => {
        list.value[list.value.length - 1].loading = false;
        Toast("回答超时，请重新发送");
      })
      .finally(() => (searchLoding.value = false));
    // scrollToBottom();
    onLoad();
  }
};

const focusFunction = () => {
  setTimeout(() => {
    window.scrollTo(0, document.body.sc);
  }, 300); // 等待键盘动画
};

// 生命周期钩子
onMounted(() => {
  onLoad();
  let timer = setTimeout(() => {
    showQuestion.value = true;
    clearTimeout(timer);
  }, 300);
  // 注意：这里移除了对input ref的引用，因为模板中没有input ref
  // 如果需要，可以在模板中添加ref="input"并在这里使用
  if (/iOS/i.test(navigator.userAgent)) {
    // 需要在模板中添加相应的ref
    // inputRef.value.$el.addEventListener("focus", focusFunction);
  }
});
</script>

<template>
  <div class="chat">
    <van-nav-bar title="安心修智能管家" class="nav_bar" fixed @click-left="onClickLeft" />
    <div class="main" ref="scrollContainer">
      <div class="header">
        <van-image class="header_icon" :src="anxinxiu" />
      </div>
      <div class="list">
        <!-- <div v-show="!refreshing" class="historyTips">
          {{ refirshFinish ? "没有更多历史了" : "下拉查看更多历史记录" }}
        </div> -->
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" disabled>
          <van-list v-model="loading" :finished="finished" finished-text="" :immediate-check="false">
            <!-- <van-cell v-for="item in list" :key="item" :title="item" /> -->
            <div class="common">
              <div class="chat_item system">
                <van-image class="avatar" fit="cover" round :src="avatarIcon" />
                <div class="message">
                  <div class="text_1">HI，我是您的智能养车管家~</div>
                  <div class="text_2">
                    我可以回答您关于【保养项目】、【服务预约】、【故障维修】、【爆胎处理】、【维权投诉】等相关问题。欢迎您随时向我提问哦，快来试试
                  </div>
                </div>
              </div>
              <transition name="van-slide-left">
                <div v-show="showQuestion" class="question_box">
                  <div class="header">
                    <div class="title">为您推荐以下问题</div>
                    <div class="btn">
                      <van-icon name="replay" class="btn_icon" @click="refreshQuestion" />
                      换一换
                    </div>
                  </div>
                  <div class="question_list">
                    <span v-for="(v, i) in questionList" :key="i" class="question_item" :data-index="i" :class="{
                      item_1: i == 0,
                      item_2: i == 1,
                      item_3: i == 2,
                      fadeOut: isExit,
                    }" @click="clickQuestions(v)">
                      {{ v }}
                    </span>
                  </div>
                </div>
              </transition>
            </div>
            <div v-for="(v, i) in list" :key="i" class="chat_item"
              :class="{ system: v.sendType == 3, user: v.sendType == 1 }">
              <van-image class="avatar" fit="cover" round :src="v.sendType == 3
                ? avatarIcon
                : v.sendUserAvatar
                " />
              <div class="message">
                <div class="text_2">
                  {{ v.text }}
                </div>
              </div>
              <van-loading v-if="v.loading" />
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <div class="input">
      <van-search v-model="keyword" show-action :disabled="searchLoding" placeholder="请具体详细的描述你要咨询的汽车问题"
        @search="onSearch">
        <template #action>
          <div @click="onSearch" class="search_btn">发送</div>
        </template>
      </van-search>
    </div>
  </div>
</template>



<style lang="less" scoped>
.chat {
  min-height: 100vh;
  background: url("https://zxcxappimg.oss-cn-hangzhou.aliyuncs.com//zxcxmall/2025/05/29/4431a33cd62f4efc9fc53a7606eee382.png") no-repeat;
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  box-sizing: border-box;
  padding: 160px 50px 150px 50px;
  box-sizing: border-box;
  /* 确保padding包含在高度计算内 */

  :deep(.van-nav-bar__content) {
    height: 100px;
    margin: 25px auto;
  }

  :deep(.van-nav-bar__title) {
    font-size: 54px;
    font-weight: 500;
  }

  :deep(.van-ellipsis) {
    overflow: initial;
  }

  .main {
    height: calc(100vh - 46px - 70px);
    padding-bottom: 300px;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; // iOS优化
    will-change: transform; // 硬件加速优化
    /* 增加以下属性 */
    scroll-behavior: smooth;
    scroll-padding-bottom: 20px;
    /* 预留底部空间 */
    contain: layout;
    /* 防止内容跳动 */

    overscroll-behavior: contain;

    /* 防止滚动链 */
    .header {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      .header_icon {
        width: 190px;
        height: 101px;
      }
    }

    .list {
      margin-top: 30px;

      .historyTips {
        font-size: 32px;
        color: #898989;
        margin-bottom: 50px;
        text-align: center;
      }

      .common {
        margin: 20px 0;

        .question_box {
          margin-top: 80px;
          border: 1px solid #eef4ff;
          padding: 60px 50px;
          background: #eef4ff;
          border-radius: 30px;

          .header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .title {
              font-size: 50px;
              color: #406dfc;
            }

            .btn {
              display: flex;
              align-items: center;

              .btn_icon {
                margin-right: 10px;
                font-size: 50px;
              }

              font-size: 38px;
              color: #999999;
            }
          }

          .question_list {
            display: flex;
            flex-direction: column;
            margin-top: 30px;
          }

          .question_item {
            padding: 15px 30px;
            border-radius: 10px;
            color: #fff;
            background: #406dfc;
            font-size: 38px;
            max-width: 500px;
            text-align: center;
            opacity: 0;
            animation: enterAnim 0.8s forwards;
            transform: translateX(-50px);
          }

          .item_1 {
            animation-delay: 0.3s;
          }

          .item_2 {
            margin: 40px 0 40px 20%;
            animation-delay: 0.6s;
          }

          .item_3 {
            margin-left: 40%;
            animation-delay: 0.9s;
          }
        }
      }

      .chat_item {
        display: flex;
        align-items: start;
        width: 100%;
        margin: 40px 0;

        .avatar {
          min-width: 150px;
          max-width: 150px;
          height: 150px;
        }

        .message {
          padding: 30px 25px;
          border-radius: 20px;
          flex-grow: 1;
          max-width: 60%;

          .text_1 {
            font-size: 50px;
            color: #303030;
            font-weight: bold;
            margin-bottom: 20px;
          }

          .text_2 {
            font-size: 38px;
            color: #666666;
          }
        }
      }

      .system {
        justify-content: start;

        .message {
          margin-left: 30px;
          background: #fff;
        }
      }

      .user {
        flex-direction: row-reverse;

        // justify-content: flex-end;
        .message {
          margin-right: 30px;
          background: #406dfc;

          .text_2 {
            color: #fff;
          }
        }
      }
    }
  }

  .input {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 30px 30px 90px 30px;
    background: #fff;
    z-index: 99;

    :deep(.van-search) {
      padding: 0;
    }

    .search_btn {
      font-size: 38px;
      padding: 0 40px;
      background: #406dfc;
      border-radius: 10px;
      height: 100px;
      line-height: 100px;
      color: #fff;
    }
  }

  .nav_bar {
    :deep(.van-icon) {
      font-size: 50px;
      font-weight: bold;
      color: #333333;
    }
  }

  /* 退出动画 */
  .fadeOut {
    animation: exit 0.8s !important;
  }

  /* 动画关键帧 */
  @keyframes enterAnim {
    to {
      opacity: 1;
      transform: translateX(calc(20px * var(--index)));
    }
  }

  /* 通过属性选择器设置偏移 */
  .question_item[data-index="0"] {
    --index: 0;
  }

  .question_item[data-index="1"] {
    --index: 1;
  }

  .question_item[data-index="2"] {
    --index: 2;
  }

  @keyframes exit {
    to {
      opacity: 0;
      transform: translateX(calc(100% + 50px * var(--index)));
    }
  }
}

:deep(.van-search__field) {
  height: 120px;
}

:deep(.van-field__left-icon .van-icon) {
  font-size: 55px;
}

:deep(.van-cell__value) {
  font-size: 44px;
}
</style>
